﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using STT.Business;
using STT.Entities;
using System.Data;
using System.IO;

namespace STT.Admin.UserControls
{
    public partial class ucThemGiangVien : System.Web.UI.UserControl
    {
        public static DataTable tbStatic;

        public bool chonSuaClick;
        string Ma_GV = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            // Load du lieu cac dropdown list
            Loanddl();

            // Mang tinh xu ly ngoai ngu giang vien
            if (tbStatic==null)
            {
                tbStatic = new DataTable();
                tbStatic.Columns.Add("MaNgoaiNgu", typeof(int));               
                tbStatic.Columns.Add("NgayCap", typeof(DateTime));
                tbStatic.Columns.Add("NoiCap", typeof(string));
                tbStatic.Columns.Add("TenDN", typeof(string));
            }

            btThemMoi.Visible = true;
            btSua.Visible = false;

            if (Request.QueryString["idgv"] != null && Request.QueryString["idgv"].ToString().Trim()!="")
            {                
                // An nut them moi
                btThemMoi.Visible = false;
                btSua.Visible = true;

                // Lay ma giang vien
                Ma_GV = Request.QueryString["idgv"].ToString().Trim();
                
                // Lay thong ngu giang vien
                //tbStatic = ;

                gvNgoaiNgu.DataSource = BTbGiangVien_NgoaiNgu.SelectByMaGV(Ma_GV);
                gvNgoaiNgu.DataBind();
                try
                {
                    ETbGiangVien gv = BTbGiangVien.SelectByIDGV(Ma_GV);

                    // Hien thi thong tin giang vien
                    txtTenGiangVien.Text = gv.TenGV;
                    txtDiaChi.Text = gv.DiaChi;
                    txtGhiChu.Text = gv.GhiChu;
                    txtSDT.Text = gv.Sdt.TrimEnd();
                    txtSoCMT.Text = gv.SoCMT.TrimEnd();

                    ddChucVu.SelectedValue = gv.MaChucVu.ToString();
                    ddChuyenMon.SelectedValue = gv.MaTDChuyenMon.ToString();
                    ddDonVi.SelectedValue = gv.MaDonVi.ToString();
                    ddHocVan.SelectedValue = gv.MaTDHocVan.ToString();

                    // Lay thong tin giang vien


                    if (gv.Anh.ToString().Trim() == "")
                    {
                        anhDaiDien.ImageUrl = "~/Uploads/Avatar/avatar-default.jpg";
                    }
                    else
                    {
                        anhDaiDien.ImageUrl = "~/Uploads/Avatar/" + gv.Anh.TrimEnd();
                        imgAnhDaiDienCu.Value = gv.Anh.TrimEnd();
                    }
                }
                catch  
                {
                }
                
            }
            else
            {
                gvNgoaiNgu.DataSource = tbStatic;
                gvNgoaiNgu.DataBind();
            }
        }
        void Loanddl()
        {
            Methods.ChucVu(ref ddChucVu);
            Methods.ChuyenMon(ref ddChuyenMon);
            Methods.DonViGiangVien(ref ddDonVi, Session["TenDN"].ToString());
            Methods.HocVan(ref ddHocVan);

        }
        void LoadNgoaiNguGiangVien()
        {
            gvNgoaiNgu.AutoGenerateColumns = false;
            gvNgoaiNgu.DataSource = BTbGiangVien_NgoaiNgu.SelectByMaGV(Ma_GV);
            gvNgoaiNgu.DataBind();
        }

        void ThongBao(string Loi)
        {
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!", "<script>alert('" + Loi + "')</script>", false);
        }

        protected void btSua_Click(object sender, EventArgs e)
        {
            if (KiemTraDuLieu(Ma_GV))
            {
                ThongBao("Một đơn vị không thể có 2 Giám đốc.");
                return;
            }

            string id = "";

            if (upAnhDaiDien.HasFile)
            {
                id = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString() + "¿" + upAnhDaiDien.FileName;
                try
                {
                    File.Delete(Path.Combine(Server.MapPath("~/Uploads/Avatar/")+imgAnhDaiDienCu.Value));
                }
                catch
                {}

                upAnhDaiDien.SaveAs(Path.Combine(Server.MapPath("~/Uploads/Avatar/"), id));
            }
            else
                id = imgAnhDaiDienCu.Value;
            

            BTbGiangVien.Update(new ETbGiangVien
            {
                MaGV = Ma_GV,
                TenGV = txtTenGiangVien.Text,
                Sdt = txtSDT.Text,
                DiaChi = txtDiaChi.Text,
                MaDonVi = Int32.Parse(ddDonVi.SelectedValue),
                MaChucVu = Int32.Parse(ddChucVu.SelectedValue),
                SoCMT = txtSoCMT.Text,
                MaTDChuyenMon = Int32.Parse(ddChuyenMon.SelectedValue),
                MaTDHocVan = Int32.Parse(ddHocVan.SelectedValue),
                GhiChu = txtGhiChu.Text,
                Anh = id
            });

            Session["action"] = 2;
            Response.Redirect("~/Admin/Default.aspx?idpage=dsgv", true);
        }

        bool KiemTraDuLieu(string Ma_GV)
        {
           // ThongBao(ddDonVi.SelectedValue + " " + ddChucVu.SelectedValue);

            return BTbGiangVien.KiemTraDuLieu(new ETbGiangVien
            {
                MaGV=Ma_GV,
                MaDonVi = int.Parse(ddDonVi.SelectedValue),
                MaChucVu = int.Parse(ddChucVu.SelectedValue),
            });
        }      

        protected void gvNgoaiNgu_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.Footer || e.Row.RowType == DataControlRowType.EmptyDataRow)
            //{
            DropDownList dd = e.Row.FindControl("ddlTenNgoaiNgu") as DropDownList;

            if (dd != null)
                Methods.NgoaiNgu(ref dd);

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                dd.SelectedValue = DataBinder.Eval(e.Row.DataItem, "MaNgoaiNgu").ToString();
            }
            // }
        }

        protected void btThemMoiNgoaiNgu_Click(object sender, EventArgs e)
        {
            Control control = null;
            if (gvNgoaiNgu.FooterRow != null)
            {
                control = gvNgoaiNgu.FooterRow;
            }
            else
            {
                control = ((Control)sender).Parent;
            }

            DropDownList ddlTen = (DropDownList)control.FindControl("ddlTenNgoaiNgu");
            TextBox txtNgay = (TextBox)control.FindControl("txtNgayCap");
            TextBox txtNoi = (TextBox)control.FindControl("txtNoiCap");

            if (Ma_GV == "")
            {
                if (tbStatic.Rows.Count > 0)
                {
                    DataRow[] rows;
                    rows = tbStatic.Select("MaNgoaiNgu=" + ddlTen.SelectedValue.TrimEnd() + " AND TenDN='" + Session["TenDN"].ToString() + "'");

                    if (rows.Length > 0)
                    {
                        ThongBao("Đã tồn tại ngoại ngữ.");
                        return;
                    }
                }

                DataRow row = tbStatic.NewRow();
                row["MaNgoaiNgu"] = ddlTen.SelectedValue;
                row["NgayCap"] = DateTime.Parse(txtNgay.Text);
                row["NoiCap"] = txtNoi.Text;
                row["TenDN"] = Session["TenDN"].ToString();

                tbStatic.Rows.Add(row);

                gvNgoaiNgu.DataSource = tbStatic;
                gvNgoaiNgu.DataBind();
            }
            else
            {
                // Kiem tra su ton tai ngoai ngu
                try
                {
                    // Them moi ngoai ngu
                    BTbGiangVien_NgoaiNgu.Insert(new ETbGiangVien_NgoaiNgu
                     {
                         MaGV = Ma_GV,
                         NgayCap = DateTime.Parse(txtNgay.Text),
                         MaNgoaiNgu = int.Parse(ddlTen.SelectedValue),
                         NoiCap = txtNoi.Text,
                         TrangThai = 1
                     });

                    LoadNgoaiNguGiangVien();
                }
                catch
                { ThongBao("Đã tồn tại ngoại ngữ."); }
            }
        }

        protected void gvNgoaiNgu_RowDeleting1(object sender, GridViewDeleteEventArgs e)
        {
            int MaNN = int.Parse(gvNgoaiNgu.DataKeys[e.RowIndex].Value.ToString());

            if (Ma_GV == "")
            {
                DataRow[] rows;
                rows = tbStatic.Select("MaNgoaiNgu=" + MaNN + "AND TenDN='" + Session["TenDN"].ToString() + "'");

                foreach (DataRow r in rows)
                    r.Delete();

                gvNgoaiNgu.DataSource = tbStatic;
                gvNgoaiNgu.DataBind();
            }
            else
            {
                BTbGiangVien_NgoaiNgu.Delete(Ma_GV, MaNN);
                LoadNgoaiNguGiangVien();
            }
        }

        protected void btThemMoi_Click(object sender, EventArgs e)
        {
            string MaGV = "GV" + BTbGiangVien.TaoMaGV();
          
            if (KiemTraDuLieu(MaGV))
            {
                ThongBao("Một đơn vị không thể có 2 Giám đốc.");
                return;
            }
            string id = "";
            if (upAnhDaiDien.HasFile)
            {
                id = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString() + "¿" + upAnhDaiDien.FileName;
                upAnhDaiDien.SaveAs(Path.Combine(Server.MapPath("~/Uploads/Avatar/"), id));
            }
            // Them vao bang giang vien
            BTbGiangVien.Insert(new ETbGiangVien
            {
                MaGV=MaGV,
                TenGV = txtTenGiangVien.Text,
                Sdt = txtSDT.Text,
                DiaChi = txtDiaChi.Text,
                MaDonVi = Int32.Parse(ddDonVi.SelectedValue),
                MaChucVu = Int32.Parse(ddChucVu.SelectedValue),
                SoCMT = txtSoCMT.Text,
                MaTDChuyenMon = Int32.Parse(ddChuyenMon.SelectedValue),
                MaTDHocVan = Int32.Parse(ddHocVan.SelectedValue),
                GhiChu = txtGhiChu.Text,
                Anh=id,
                NguoiTao=Session["TenDN"].ToString()
            });

            // Them bang giang vien ngoai ngu
            DataRow[] tb = tbStatic.Select("TenDN='" + Session["TenDN"].ToString() + "'");

            int count = tb.Length;
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    BTbGiangVien_NgoaiNgu.Insert(new ETbGiangVien_NgoaiNgu
                    {
                        MaGV = MaGV,
                        MaNgoaiNgu = int.Parse(tb[i]["MaNgoaiNgu"].ToString()),
                        NgayCap = DateTime.Parse(tb[i]["NgayCap"].ToString()),
                        NoiCap = tb[i]["NoiCap"].ToString(),
                        TrangThai = 1
                    });

                    // Xoa bang sau khi them
                    tb[i].Delete();
                }
            }

            // Tao tai khoan cho giang vien
            BTbDangNhap dn=new BTbDangNhap();

            BTbDangNhap.Insert(new ETbDangNhap
            {
                TenDangNhap=MaGV,
                MatKhau=dn.GetMD5("12345678"),
                Quyen="5",
                RadomPass=dn.Radomchar(),
                KhoaTaiKhoan=0           
            });

            Session["action"] = 1;

            Response.Redirect("~/Admin/Default.aspx?idpage=dsgv", true);
        }
    }
}